package util;

import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class MyMapListHandler extends MapListHandler {
    @Override
    protected Map<String, Object> handleRow(ResultSet rs) throws SQLException {
        Map<String, Object> maps = new HashMap<>(16);
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        for (int i = 1; i <= columnCount; i++) {
            String columnLabel = metaData.getColumnLabel(i);
            // 将字段转换成驼峰
            String label= underLine2CamalCase(columnLabel);
            maps.put(label, rs.getObject(i));
        }
        return maps;
    }

    /**
     * 下划线转驼峰
     * @param columnLabel
     * @return
     */
    private String underLine2CamalCase(String columnLabel){
        if(columnLabel.contains("_") && !columnLabel.startsWith("_") && !columnLabel.endsWith("_")){
            String[] s = columnLabel.split("_");
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < s.length; i++) {
                if (i == 0){
                    stringBuilder.append(s[i]);
                    continue;
                }
                stringBuilder.append(String.valueOf(s[i].charAt(0)).toUpperCase());
                stringBuilder.append(s[i].substring(1));
            }
            return stringBuilder.toString();
        }
        return columnLabel;
    }
}
